package com.band.manager.controller;

import com.band.manager.constant.CommonResult;
import com.band.manager.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(value="测试登陆管理器",tags = {"测试登陆管理器"})
@RequestMapping(value = "/login")
@Slf4j
public class loginController {
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation(value = "登录",httpMethod = "POST")
    public CommonResult login(@RequestParam String username, String password, Model model){
        User user = User.builder().username(username).password(password).build();
//        SimpleHash md5 = new SimpleHash("MD5",user.getPwd(),null,1);
//        pwd = md5.toString();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),password);

        String msg = null;
        try{
            subject.login(token);
        } catch (UnknownAccountException uae) {
            msg = "未知账户";
        } catch (IncorrectCredentialsException ice) {
            msg = "密码不正确";
        } catch (LockedAccountException lae) {
            msg = "账户已锁定";
        } catch (ExcessiveAttemptsException eae) {
            msg = "用户名或密码错误次数过多";
        } catch (AuthenticationException ae) {
            msg = "用户名或密码不正确";
        }

        // 判断登录是否成功
        if (subject.isAuthenticated()) {
            return CommonResult.success(subject.getSession().getId().toString(),msg);
        } else {
            token.clear();
            return CommonResult.failed(msg);
        }
    }

    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    @ApiOperation(value = "退出登录", httpMethod = "POST")
    public CommonResult logout(){
        Subject subject = SecurityUtils.getSubject();
        log.info(subject.getPrincipal().toString());
        SecurityUtils.getSubject().logout();
        return CommonResult.success("退出成功");
    }

}
